package com.hy.reggie.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hy.reggie.current.R;
import com.hy.reggie.current.SendMailCode;
import com.hy.reggie.pojo.User;
import com.hy.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private SendMailCode sendMailCode;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 发送手机短信验证码（邮件验证码）
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request) {
        //获取手机号
        String phone = user.getPhone();

        if (!StringUtils.isEmpty(phone)) {
            //发送邮件
            String code = sendMailCode.send(phone);

            log.info("验证码为：{}", code);

            //将生成的验证码保存到Session
//            HttpSession session = request.getSession();
//            session.setAttribute("code", code);
//            session.setMaxInactiveInterval(300);

            //将生成的验证码存到Redis中，并设置有效期5分钟
            ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
            valueOperations.set("mailCode", code, 5, TimeUnit.MINUTES);
            return R.success("发送成功");
        }

        return R.success("发送失败");
    }

    /**
     * 登录
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map user, HttpServletRequest request) {
        log.info(user.toString());

        //获取手机号
        String phone = user.get("phone").toString();

        //获取验证码
        String code = user.get("code").toString();

//        从Session中获取保存的验证码
//        Object codeInSession = request.getSession().getAttribute("code");

        //从redis中获取验证码
        ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
        String codeInSession = valueOperations.get("mailCode");

        //进行比对
        if (codeInSession != null && codeInSession.equals(code)) {
            //比对成功则登陆成功
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User one = userService.getOne(queryWrapper);
            if (one == null) {
                //判断是否为新用户
                User user1 = new User();
                user1.setPhone(phone);
                user1.setStatus(1);
                userService.save(user1);
            }
            request.getSession().setAttribute("user", one.getId());

            //如果用户登陆成功，删除redis中缓存的验证码
            redisTemplate.delete("mailCode");
            return R.success(one);
        }
        return R.error("验证码错误");
    }
}
